package ln.gather.jsr.jcache.management;

import javax.cache.Cache;
import javax.cache.configuration.CompleteConfiguration;
import javax.cache.management.CacheMXBean;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.Hashtable;

public interface ManagementUtils {

    static CacheMXBean adaptCacheMXBean(CompleteConfiguration<?, ?> configuration) {
        return new CacheMXBeanAdapter(configuration);
    }

    static <K, V> ObjectName createObjectName(Cache<K, V> cache, String type) {
        Hashtable<String, String> props = new Hashtable<>();
        props.put("type", type);
        props.put("name", cache.getName());
        props.put("uri", getUri(cache));
        ObjectName objectName;
        try {
            objectName = new ObjectName("javax.cache", props);
        } catch (MalformedObjectNameException e) {
            throw new RuntimeException(e);
        }
        return objectName;
    }

    static <V, K> String getUri(Cache<K, V> cache) {
        URI uri = cache.getCacheManager().getURI();
        try {
            return URLEncoder.encode(uri.toASCIIString(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }


}
